package org.jeecg.modules.xxgx.common.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.common.util.LoginUserUtil;
import org.jeecg.modules.common.util.MathUtil;
import org.jeecg.modules.innerApi.bwgfApi.service.IBaiWangSkfpService;
import org.jeecg.modules.innerApi.common.requestDto.CommonParam;
import org.jeecg.modules.innerApi.common.requestDto.CurrentFphmParam;
import org.jeecg.modules.innerApi.common.requestDto.DpdlParam;
import org.jeecg.modules.innerApi.common.requestDto.FaceImgParam;
import org.jeecg.modules.innerApi.common.responseDto.*;
import org.jeecg.modules.innerApi.zhiYunApi.service.IZhiyunSkfpService;
import org.jeecg.modules.innerApi.zhiYunSdApi.service.IZhiyunSdfpService;
import org.jeecg.modules.xxgx.common.enums.KpzdkpmsEnum;
import org.jeecg.modules.xxgx.common.enums.KpzdlxEnum;
import org.jeecg.modules.xxgx.common.enums.KpzdztEnum;
import org.jeecg.modules.xxgx.common.service.IXxBase;
import org.jeecg.modules.xxgx.fpgl.dto.XxApifpDownloadDto;
import org.jeecg.modules.xxgx.fpgl.entity.CsXxFpxx;
import org.jeecg.modules.xxgx.fpgl.service.ICsXxFpxxService;
import org.jeecg.modules.xxgx.fpgl.vo.CsXxFpjfVO;
import org.jeecg.modules.xxgx.fpgl.vo.XxApifpDownloadParam;
import org.jeecg.modules.xxgx.kpzdgl.entity.CsXxKpzd;
import org.jeecg.modules.xxgx.kpzdgl.service.ICsXxKpzdService;
import org.jeecg.modules.xxgx.sxed.entity.CsXxSxed;
import org.jeecg.modules.xxgx.sxed.service.ICsXxSxedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 销项基础服务
 */
@Transactional
@Service
@Slf4j
public class XxbaseImpl implements IXxBase {

    @Autowired
    private IZhiyunSkfpService zhiyunSkfpService;

    @Autowired
    private IBaiWangSkfpService baiWangSkfpService;

    @Autowired
    private ICsXxKpzdService kpzdService;
    @Autowired
    private IZhiyunSdfpService zhiyunSdfpService;
    @Autowired
    private ICsXxSxedService sxedService;

    @Autowired
    private ICsXxFpxxService iCsXxFpxxService;

    /***
     * 智能赋码
     * @param spmc 商品名称
     */
    public Result<List<ZnfmRtn>> znfm(String spmc){
        //百旺智能赋码失败后，调用智云智能赋码
        Result result= baiWangSkfpService.getZnfm(spmc);
        if(!result.isSuccess()){
            log.info("百旺接口赋码失败："+result.getMessage());
            result=zhiyunSkfpService.znfm(spmc);
            if(!result.isSuccess()){
                log.info("智云接口赋码失败："+result.getMessage());
            }
        }
        return result;
    }

    /***
     * 云抬头检索
     * @param searchName 企业名称
     */
    public Result<JSONArray> comSearch(String searchName){
        //百旺云抬头检索
        return baiWangSkfpService.getComSearch(searchName);
    }

    /***
     * 获取税控、数电纸质发票当前发票号码、发票代码
     * @param param 企业名称
     */
    public Result<CurrentFphmRtn.CurrentFphmRtnData> currentFphm(CurrentFphmParam param){
        CommonParam commonParam=kpzdService.getCommonParamByKpzd(param.getKpzddm());
        //完善开票终端、企业信息、服务器信息
        param.setKpzd(commonParam.getKpzd());
        param.setQyxx(commonParam.getQyxx());
        param.setFwqxx(commonParam.getFwqxx());
        String zdlx=commonParam.getKpzd().getZdlx();
        CurrentFphmRtn rtn=null;
        if(zdlx.equals(KpzdlxEnum.sdzd.getValue())){//数电纸质发票获取
             String kpms=commonParam.getKpzd().getKpms();
             if(kpms.equals(KpzdkpmsEnum.sdtd.getValue())) {
                 rtn = zhiyunSdfpService.getCurrentFphm(param);
             }
        }else{//税控发票获取
             rtn=zhiyunSkfpService.getCurrentFphm(param);
        }
        if(rtn.getSuccess()){
            return Result.OK("获取成功",rtn.getData());
        }else {
            return Result.error("获取失败："+rtn.getMsg());
        }
    }
    /***
     * 获取税控、数电开票终端
     * @param nsrmc 企业名称
     * @param nsrsbh 企业税号
     */
    public Result<List<CsXxKpzd>> getKpzd(String nsrmc, String nsrsbh){
        if(StringUtils.isEmpty(nsrsbh)){
            return Result.error("获取终端失败：企业税号不能为空");
        }
        List<CsXxKpzd> list=kpzdService.lambdaQuery().eq(CsXxKpzd::getNsrsbh,nsrsbh).list();
        if(list==null&&list.size()==0){
            return Result.error("获取终端失败：未查询到"+nsrmc+"可用的开票终端");
        }else{
            return Result.OK("查询成功",list);
        }
    }
    /***
     * 获取税控、数电开票终端
     * @param kpzddm 开票终端代码
     */
    public Result<CsXxKpzd> getKpzd(String kpzddm){
        List<CsXxKpzd> kpzds=kpzdService.lambdaQuery().eq(CsXxKpzd::getZddm,kpzddm).list();
        if(kpzds==null&&kpzds.size()==0){
            return Result.error("获取终端失败：未查询到可用的开票终端");
        }else{
            return Result.OK("查询成功",kpzds.get(0));
        }
    }
    /***
     * 数电平台登录
     * @param kpzddm 开票终端代码
     * @param dllx 1：短信验证登录 2：人脸二维码登录 3：税务 app 扫码登录
     * @param verify  二次登录验证值:短信登录，传短信验证码；二维码登录传二维码id
     */
    public Result loginDppt(String kpzddm,String dllx,String verify){
        //        模拟数据
//        CommonRtn commonRtn = new CommonRtn();
//        commonRtn.setSuccess(true);
//        if(StringUtils.isEmpty(sms)){
//            commonRtn.setSuccess(false);
//            commonRtn.setCode("301");//重复登录
//            commonRtn.setMsg("验证码已发送到手机号：176****2696");
//        }else{
//            commonRtn.setSuccess(false);
//            commonRtn.setMsg("失败");
//        }
//        if (commonRtn.getSuccess()) {
//            return Result.OK(commonRtn.getMsg());
//        } else {
//            return Result.error(Integer.valueOf(commonRtn.getCode()),commonRtn.getMsg());
//        }
        CommonParam commonParam = kpzdService.getCommonParamByKpzd(kpzddm);
        //登录时前通过查询授信额度判断当前登录账号是否已在线，若在线情况下不能进行重复登录
        CreditRtn creditRtn = zhiyunSdfpService.getCreditLine(commonParam.getKpzd().getNsrsbh(),commonParam);
        if(creditRtn.getSuccess()){
            String msg="开票人："+commonParam.getKpzd().getKpr()+"对应的终端："+commonParam.getKpzd().getZdmc()+"已登录，请务重复登录";
            return Result.error(CommonConstant.DPPT_DL_CF,msg);//重复登录
        }else {
            CsXxKpzd csXxKpzd = commonParam.getKpzd();
            DpdlParam dpdlParam = new DpdlParam();
            dpdlParam.setNsrsbh(csXxKpzd.getNsrsbh());
            dpdlParam.setUsername(csXxKpzd.getDzswjzh());
            dpdlParam.setPassword(csXxKpzd.getDzswjmm());
            if(StringUtils.isEmpty(dllx)||dllx.equals("1")){
                dpdlParam.setSms(verify);
            }else if(dllx.endsWith("2")){//人脸二维码登录{
                dpdlParam.setEwmlx("1");
                dpdlParam.setEwmid(verify);
            }else if(dllx.endsWith("3")){//税务 app 扫码登录
                dpdlParam.setEwmlx("10");
                dpdlParam.setEwmid(verify);
            }
            dpdlParam.setKpzd(commonParam.getKpzd());
            dpdlParam.setQyxx(commonParam.getQyxx());
            dpdlParam.setFwqxx(commonParam.getFwqxx());
            DpdlRtn dpdlRtn = zhiyunSdfpService.login(dpdlParam);
            if (dpdlRtn.getSuccess()) {
                if(StringUtils.isNotEmpty(verify)){
                    csXxKpzd.setZxzt(KpzdztEnum.zx.getValue());
                    csXxKpzd.setDlsj(new Date());
                    kpzdService.updateById(csXxKpzd);
                }
                return Result.OK(dpdlRtn.getMsg(),dpdlRtn.getData());
            } else {
                return Result.error(dpdlRtn.getMsg());
            }
        }
    }
    /***
     * 数电实名认证二维码
     * @param kpzddm 开票终端代码
     * @param ermlx 二维码类型：1值为税局 app 二维码 2 获取个人所得税二维码
     */
    public Result getSmrzEwm(String kpzddm,String ermlx){
        CommonParam commonParam = kpzdService.getCommonParamByKpzd(kpzddm);
        CsXxKpzd csXxKpzd = commonParam.getKpzd();

        FaceImgParam param = new FaceImgParam();
        param.setNsrsbh(csXxKpzd.getNsrsbh());
        param.setType(ermlx);
        param.setKpzd(commonParam.getKpzd());
        param.setQyxx(commonParam.getQyxx());
        param.setFwqxx(commonParam.getFwqxx());
        //模拟数据
//        FaceImgRtn faceImgRtn = new FaceImgRtn();
//        faceImgRtn.setSuccess(true);
//        faceImgRtn.setMsg("成功");
//        FaceImgRtn.FaceImgRtnData rtnData = new FaceImgRtn.FaceImgRtnData();
//        rtnData.setNsrsbh("11111111111111111");
//        rtnData.setSlzt("1");
//        rtnData.setEwmly("swj");
//        byte[] ewmBytes = new byte[0];
//        try {
//            ewmBytes = QRCodeUtil.encode("111111111111", 200, 200);
//        } catch (Exception e) {
//            throw new JeecgBootException(e.getMessage());
//        }
//        String ewmBase64 = Base64.getEncoder().encodeToString(ewmBytes);
//        rtnData.setEwm(ewmBase64);
//        faceImgRtn.setData(rtnData);
        FaceImgRtn faceImgRtn = zhiyunSdfpService.getFaceImg(param);
        if(faceImgRtn.getSuccess()){
            return Result.OK("获取成功",faceImgRtn.getData());
        }else{
            return Result.error(faceImgRtn.getMsg());
        }
    }
    /***
     * 授信额度查询
     * @param kpzddm 终端代码
     */
    public Result getCredit(String kpzddm){
        CommonParam commonParam = kpzdService.getCommonParamByKpzd(kpzddm);
        CsXxKpzd csXxKpzd = commonParam.getKpzd();

        CreditRtn creditRtn = zhiyunSdfpService.getCreditLine(csXxKpzd.getNsrsbh(),commonParam);
        if (creditRtn.getSuccess()) {
            CreditRtn.CreditRtnData creditRtnData=creditRtn.getData();
            LoginUser user=LoginUserUtil.getLoginUser();
            BigDecimal zsxed=new BigDecimal(creditRtnData.getZsxed());
            BigDecimal sysxed=new BigDecimal(creditRtnData.getSysxed());
            BigDecimal ysysxed=MathUtil.sub(zsxed,sysxed);
            //更新本地存储的授信额度信息
            List<CsXxSxed> csXxSxeds=sxedService.lambdaQuery().eq(CsXxSxed::getCompanyId,csXxKpzd.getCompanyId()).list();
            if(csXxSxeds!=null&&csXxSxeds.size()>0){
                CsXxSxed sxed=csXxSxeds.get(0);
                sxed.setZsxed(zsxed);
                sxed.setYysxed(ysysxed);
                sxed.setSysxed(sysxed);
                sxed.setDqsxsq(new Date());
                sxed.setEdgxrq(new Date());
                if(user!=null) {
                    sxed.setUpdateBy(user.getUsername());
                    sxed.setUpdateTime(new Date());
                }
                sxed.getUpdateBy();
                sxedService.updateById(sxed);
            }else{
                CsXxSxed sxed=new CsXxSxed();
                sxed.setZsxed(zsxed);
                sxed.setYysxed(ysysxed);
                sxed.setSysxed(sysxed);
                sxed.setEdgxrq(new Date());
                sxed.setDqsxsq(new Date());
                sxed.setNsrsbh(csXxKpzd.getNsrsbh());
                sxed.setCompanyId(csXxKpzd.getCompanyId());
                sxed.setTenantId(csXxKpzd.getTenantId());
                if(user!=null) {
                    sxed.setCreateBy(user.getUsername());
                    sxed.setCreateTime(new Date());
                    sxed.setSysOrgCode(user.getOrgCode());
                }
                sxedService.save(sxed);
            }
            return Result.OK("授信额度获取成功",creditRtn.getData());
        } else {
            return Result.error(Integer.valueOf(creditRtn.getCode()),"授信额度获取失败："+creditRtn.getMsg());
        }
    }

    @Override
    public Result<XxApifpDownloadDto> fpDownload(XxApifpDownloadParam param) {
        XxApifpDownloadDto dto = new XxApifpDownloadDto();
        String fphm = param.getFphm();
        String fpdm = param.getFpdm();
        String kpzddm = param.getKpzddm();
        CommonParam commonParam = kpzdService.getCommonParamByKpzd(kpzddm);
        if (commonParam.getKpzd() == null) {
            throw new JeecgBootException("根据kpzddm：" + param.getKpzddm() + "未查询到对应的终端,请核实");
        }
        QueryWrapper<CsXxFpxx> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(fphm),"fphm",fphm);
        queryWrapper.eq(StringUtils.isNotBlank(fpdm),"fpdm",fpdm);
        queryWrapper.eq("company_id",commonParam.getKpzd().getCompanyId());
        List<CsXxFpxx> fpxxlist = iCsXxFpxxService.list(queryWrapper);
        if(fpxxlist.isEmpty()){
            throw new JeecgBootException("根据发票号码:" + param.getFphm() + ",未查询到发票！");
        }
        CsXxFpxx csXxFpxx = fpxxlist.get(0);
        Result<CsXxFpjfVO> bswj = iCsXxFpxxService.getBswj(csXxFpxx.getId());
        if(bswj.isSuccess()){
            CsXxFpjfVO result = bswj.getResult();
            if("1".equals(param.getFileType())){
                dto.setPdf(result.getPdfdz());
            }else if("2".equals(param.getFileType())){
                dto.setOfd(result.getOfddz());
            }else if("3".equals(param.getFileType())){
                dto.setXml(result.getXmldz());
            }else{
                throw new JeecgBootException("未知的fileType类型！");
            }
        }else{
            throw new JeecgBootException(bswj.getMessage());
        }
        return Result.OK(dto);
    }
}
